/**
 * 
 */
package com.fclassroom.logger.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.github.pagehelper.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 处理Jason日志数据格式
 * 
 * @author zb
 * @Time 2017年6月1日 下午3:17:22
 */
public class JasonUtil {
	protected static final Logger log = LogManager.getLogger();

	/**
	 * 将Jason数据转换为json格式
	 * 
	 * @param JasonStr
	 *            埋点日志data
	 * @return
	 */
	public static String toJson(String jasonStr) {
		if (StringUtil.isEmpty(jasonStr)) {
			log.error("jason数据为空。");
			return "";
		}
		jasonStr = jasonStr.replaceAll("\r|\n", "");// 教师端出现日志末尾加了换行，导致转换失败，做如此修改
		if (jasonStr.contains("\\")) {
			jasonStr = jasonStr.replace("\\", "");// 优化，否则转换json失败
		}
		String REGEX = "\\|[\\w]+:";// \\|[\\w]+:

		StringBuffer oldStr = new StringBuffer();
		StringBuffer newStr = new StringBuffer();
		String findStr = "";
		String returnJson = "";
		try {
			Pattern p = Pattern.compile(REGEX);
			// get a matcher object
			Matcher m = p.matcher(jasonStr);
			while (m.find()) {
				findStr = m.group();
				findStr = findStr.substring(1, findStr.length() - 1);
				oldStr = oldStr.append("|").append(findStr).append(":");
				newStr = newStr.append("\",\"").append(findStr).append("\":\"");
				jasonStr = jasonStr.replace(oldStr, newStr);
				oldStr.setLength(0);
				newStr.setLength(0);
			}
			jasonStr = jasonStr.replaceFirst(":", "\":\"");
			returnJson = "{\"" + jasonStr + "\"}";
			returnJson = returnJson.replace("\"{", "[{");
			returnJson = returnJson.replace("}\"", "}]");
		} catch (Exception e) {
			log.error("error:" + e.getMessage());
			e.printStackTrace();
		}
		return returnJson;
	}

	public static void main(String args[]) {
		// String log = "loglevel:ERROR|createtime:2017-06-01
		// 09:39:43|userid:null|username:dashuju001|sessionid:null|cid:null|ctype:1|userip:218.4.251.46|useend:11|eventtype:jk_click|functionname:测试|cururl:登录极课|position:江苏省苏州市|equipmentpara:{\"word\":\"Office07,
		// Office16\",\"addIn\":\"1.7.1.0\"}|content:{\"modulename\":\"网络设置\",\"systemversion\":\"Microsoft
		// Windows 10 家庭中文版
		// 10.0.14393\",\"versionnum\":\"1.69.999.76\",\"networktype\":\"Internet\",\"flag\":\"0\"}|exception:{\"exceptiontype\":\"AggregateException\",\"exceptionmsg\":\"发生一个或多个错误。未将对象引用设置到对象的实例。\"}";
		String log = "loglevel:ERROR|createtime:2017-06-19 11:17:42|userid:891933|username:13656134952|sessionid:0927d07af2db7be9186e4e6d909d7f71|cid:江苏省镇江市伯先中学（初中）|ctype:1|userip:null|useend:11|eventtype:jk_click|functionname:保存|cururl:null|position:null|equipmentpara:{\"word\":\"Office07\",\"addIn\":\"1.7.1.0\"}|content:{\"modulename\":\"出卷-插件-界面操作\",\"systemversion\":\"Microsoft Windows 7 旗舰版  6.1.7601\",\"versionnum\":\"1.70.0.0\",\"networktype\":\"Internet\",\"paperid\":188254,\"subjectid\":62175,\"subjectname\":\"语文\",\"mobile\":\"13656134952\",\"checkplate\":\"考试\",\"flag\":\"0\",\"dimension\":\"按试卷\"}|exception:{\"exceptiontype\":\"COMException\",\"exceptionmsg\":\"命令失败\"}";
		String str = JasonUtil.toJson(log);
		System.out.println(str);
		JSONObject json = JSONObject.fromObject(str);
		JSONArray obj = (JSONArray) json.get("exception");
		int num = json.getInt("useend");
		String val = (String) ((JSONObject) obj.get(0)).get("exceptiontype");
		System.out.println(val);
	}
}
